package cn.com.dcsgo.listener;

import cn.com.dcsgo.constant.MqConstant;
import cn.com.dcsgo.domain.SmsLog;
import cn.com.dcsgo.model.SmsModel;
import cn.com.dcsgo.service.SmsLogService;
import com.alibaba.fastjson2.JSON;
import com.aliyun.sdk.service.dypnsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeResponseBody;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * MQ-发送手机短信监听类
 *
 * @author Dcsgo
 * @since 2025/11/11 13:36
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = MqConstant.SMS_TOPIC,
        consumerGroup = MqConstant.SMS_CONSUMER_GROUP,
        namespace = MqConstant.MQ_NAME_SPACE
)
public class ShortMessageListener implements RocketMQListener<MessageExt> {
    @Resource
    private AsyncClient asyncClient;

    @Resource
    private SmsLogService smsLogService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        SmsModel smsModel = JSON.parseObject(body, SmsModel.class);
        SendSmsVerifyCodeRequest sendSmsRequest = SendSmsVerifyCodeRequest.builder()
                .phoneNumber(smsModel.getPhoneNumber())
                .signName(smsModel.getSignName())
                .templateCode(smsModel.getTemplateCode())
                .templateParam(smsModel.getTemplateParam())
                .build();
        CompletableFuture<SendSmsVerifyCodeResponse> future = asyncClient.sendSmsVerifyCode(sendSmsRequest);
        int status = 1;
        String responseCode = "";
        try {
            SendSmsVerifyCodeResponse sendSmsResponse = future.get();
            SendSmsVerifyCodeResponseBody response = sendSmsResponse.getBody();
            responseCode = response.getCode();
            if (response.getSuccess()) {
                log.info("短信发送成功，响应结果：{}", JSON.toJSONString(response));
            } else {
                status = 0;
                log.error("短信发送失败，原因：{}", response.getMessage());
            }
        } catch (Throwable e) {
            log.error("短信发送失败，原因：{}", e.getMessage());
            status = 0;
        }
        //记录短信发送记录
        SmsLog smsLog = new SmsLog();
        smsLog.setUserPhone(smsModel.getPhoneNumber());
        smsLog.setMobileCode(smsModel.getTemplateParam());
        smsLog.setOpenId(smsModel.getOpenId());
        smsLog.setTemplateId(smsModel.getTemplateCode());
        smsLog.setResponseCode(responseCode);
        smsLog.setStatus(status);
        smsLogService.save(smsLog);
    }
}
